const http = require('http')
const url = require('url')
const path = require('path')
const fs = require('fs')
const mime = require('mime')

http.createServer((req, res) => {
  let { pathname } = url.parse(req.url)

  pathname = pathname === '/' ? 'index.html' : pathname

  

  if (/^\/api/.test(pathname)) {
    res.end('{"z": 2}')
  } else {
    // __dirname 当前文件所在的物理路径
    const fullPath = path.join(__dirname, './static', pathname)

    const ext = path.parse(fullPath).ext

    const mimeStr = mime.getType(ext)

    const content = fs.readFileSync(fullPath)

    res.writeHead(200, {
      'content-type': mimeStr
    })
    
    res.end(content)
  }
  

}).listen(8080, () => console.log('localhost:8080'))